package com.gongpingjialoan.activity.main;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Inputtips.InputtipsListener;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiItemDetail;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.gongpingjialoan.R;
import com.gongpingjialoan.adapter.SuggestionAdapter;
import com.gongpingjialoan.bean.SuggestionPlace;
import com.gongpingjialoan.utility.Utils;

import java.util.ArrayList;
import java.util.List;

public class SearchPlaceActivity extends Activity implements TextWatcher, OnClickListener {

    private EditText mKeyEditText;


    private TextView mSearchTextView;

    private ListView mSuggestionList;

    private List<SuggestionPlace> mDatas;

    private SuggestionAdapter mAdapter;

    private PoiSearch mPoiSearch;

    private PoiSearch.Query mQuery;

    private String key;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_place);
        initView();
        mDatas = new ArrayList<SuggestionPlace>();
        mAdapter = new SuggestionAdapter(SearchPlaceActivity.this, mDatas);
        mSuggestionList.setAdapter(mAdapter);

        mSuggestionList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(SearchPlaceActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                SuggestionPlace sp = mDatas.get(position);
//                String key = sp.getDetails() + sp.getStyleName().toString();
                Intent it = getIntent();
                it.putExtra("title", sp.getStyleName().toString());
                it.putExtra("detail", sp.getDetails());
                if (sp.getLatLonPoint() != null) {
                    it.putExtra("longitude", sp.getLatLonPoint().getLongitude());
                    it.putExtra("latitude", sp.getLatLonPoint().getLatitude());
                }
                setResult(RESULT_OK, it);
                finish();
            }
        });
    }

    public void initView() {
        // TODO Auto-generated method stub
        mKeyEditText = (EditText) findViewById(R.id.et_search);
        mSearchTextView = (TextView) findViewById(R.id.tv_search);
        mSuggestionList = (ListView) findViewById(R.id.lv_suggestion);

        mKeyEditText.addTextChangedListener(this);
        mSearchTextView.setOnClickListener(this);

        findViewById(R.id.title_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tv_search:
                Utils.autoCloseKeyboard(SearchPlaceActivity.this, v);
                mKeyEditText.setText("");
                mDatas.clear();
                mAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {


    }

    @Override
    public void afterTextChanged(Editable s) {
        key = s.toString().trim();
        if (!TextUtils.isEmpty(key)) {
            mSearchTextView.setVisibility(View.VISIBLE);
        } else {
            mSearchTextView.setVisibility(View.GONE);
        }
        mDatas.clear();
        mAdapter.notifyDataSetChanged();
        Inputtips inputTips = new Inputtips(this, new InputtipsListener() {
            @Override
            public void onGetInputtips(final List<Tip> tipList, int rCode) {
                if (rCode == 0) {// 正确返回
                    for (int i = 0; i < tipList.size(); i++) {
                        String name = tipList.get(i).getName();
                        final int index = i;
                        final SpannableStringBuilder sb = new SpannableStringBuilder(tipList.get(i).getName());
                        int start = name.toLowerCase().indexOf(key.toLowerCase());
                        int end = start + key.length();
                        if (start != -1) {
                            sb.setSpan(new ForegroundColorSpan(Color.parseColor("#47D1D4")), start, end,
                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                        mQuery = new PoiSearch.Query(sb.toString(), "", "");// 全国搜索

                        mQuery.setPageSize(1);// 每页查询10个
                        mQuery.setPageNum(0);// 设置查第一页
                        mPoiSearch = new PoiSearch(SearchPlaceActivity.this, mQuery);
                        mPoiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                            @Override
                            public void onPoiSearched(PoiResult poiResult, int i) {
                                SuggestionPlace sug = new SuggestionPlace();
                                if (poiResult != null && poiResult.getPois().size() > 0) {
                                    List<PoiItem> poiItems = poiResult.getPois();
                                    if (poiItems.size() > 0) {
                                        sug.setDetails(tipList.get(index).getDistrict() + poiItems.get(0).getSnippet());
                                        sug.setLatLonPoint(poiItems.get(0).getLatLonPoint());
                                    } else {
                                        sug.setDetails(tipList.get(index).getDistrict());
                                    }

                                } else {
                                    sug.setDetails(tipList.get(index).getDistrict());
                                }
                                sug.setStyleName(sb);
                                mDatas.add(sug);
                                mAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onPoiItemDetailSearched(PoiItemDetail poiItemDetail, int i) {

                            }
                        });
                        mPoiSearch.searchPOIAsyn();
                    }
                }
            }
        }
        );

        try {
            inputTips.requestInputtips(key, "");// 第一个参数表示提示关键字，第二个参数默认代表全国，也可以为城市区号
        } catch (AMapException e) {
        }

    }

}
